<?php
namespace App\Http\Controllers;
/**
 * 
 * 旅行线路下单（单买/团购:创建|参与）
 * 
 * @author shengl
 *
 */

use App\Services\TourCashierService;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
class TourCashierController extends BaseController {

    /**
     * 直接下单路线日程价格确认
     * @param TourCashierService $tourCashierService
     * @return mixed
     */
    public function initTourSingle(TourCashierService $tourCashierService){
        //线路id
        $tour_id = Input::get('tour_id');
        //线路日程id
        $schedule_id = Input::get('schedule_id',0);
        //用户id
        $user_id = Input::get('user_id');
        $traveller_ids = Input::get('traveller_ids');

        if(!$user_id || !$tour_id ||!$schedule_id){
            return $this->args_invalid();
        }
        //获取数据
        $tourData = $tourCashierService->getInitSingle($tour_id,$schedule_id,$traveller_ids,$user_id);

        if(!$tourData['result']){
            return $this->failure($tourData['msg']);
        }

        return $this->success($tourData['data']);

    }

    public function initCreateTourGroup(TourCashierService $tourCashierService){
        //线路id
        $tour_id = Input::get('tour_id');

        //线路日程id
        $schedule_id = Input::get('schedule_id',0);

        //用户id
        $user_id = Input::get('user_id');
        $traveller_ids = Input::get('traveller_ids');

        if(!$user_id || !$tour_id){
            return $this->args_invalid();
        }

        //获取数据
        $tourData = $tourCashierService->initCreateTourGroup($tour_id,$schedule_id,$traveller_ids,$user_id);

        if(!$tourData['result']){
            return $this->failure($tourData['msg']);
        }

        return $this->success($tourData['data']);
    }

    public function initJoinTourGroup(TourCashierService $tourCashierService){
        //团id
        $tuan_id = Input::get('tuan_id');

        //用户id
        $user_id = Input::get('user_id');

        $traveller_ids = Input::get('traveller_ids');

        if(!$user_id || !$tuan_id){
            return $this->args_invalid();
        }
        //获取数据
        $tourData = $tourCashierService->initJoinTourGroup($tuan_id,$user_id,$traveller_ids);

        if(!$tourData['result']){
            return $this->failure($tourData['msg']);
        }

        return $this->success($tourData['data']);
    }

    public function initByPintuan(){
        
        $user_id = Input::get('user_id');
        $store_id = Input::get('store_id',1);

        $spec_id = Input::get('spec_id');//拼团规格id

        $pintuan_id = Input::get('pintuan_id'); //拼团id

        $tuan_id = Input::get('tuan_id',0); //团id  开团默认0

        $quantity = Input::get('quantity',1);

        if (!$spec_id || !$quantity || !$pintuan_id )
        {
            return $this->failure('参数不对');
        }

        $userinfo = DB::table('member')->where('user_id',$user_id)->first();
        if(!$userinfo){
            return $this->failure("用户不存在");
        }

        if(empty($userinfo->user_name)){
            return $this->need_bind();
        }

        $pintuanService = new PintuanService();

        //检查是否可以开团或者参团
        $returnCheck = $pintuanService->checkPintuan($pintuan_id,$tuan_id,$user_id);
        if($returnCheck!= ""){
            return $this->failure($returnCheck);
        }

        /* 是否有商品 */
        $spec_info = $pintuanService->getPintuanSpec($spec_id);

        if (!$spec_info){
            return $this->failure('商品不存在');
        }

        if ($quantity > $spec_info->stock){
            return $this->failure('库存不足');
        }

        if (($spec_info->max_per_user > 0) && ($quantity > $spec_info->max_per_user)){
            return $this->failure('该商品每个人单次购买不可超过'.$spec_info->max_per_user.'件');
        }

        //编辑商品规格信息
        $spec_1 = $spec_info->spec_name_1 ? $spec_info->spec_name_1 . ':' . $spec_info->spec_1 : $spec_info->spec_1;
        $spec_2 = $spec_info->spec_name_2 ? $spec_info->spec_name_2 . ':' . $spec_info->spec_2 : $spec_info->spec_2;

        if($spec_info->spec_name_1 && $spec_info->spec_name_2){
            $specification = $spec_1 . ' ' . $spec_2;
        }else{
            $specification = '';
        }

        $configs= json_decode($spec_info->config);
        $config['shipping'] = (array)$configs->shipping;

        //编辑数据
        $temp = [
//            'store_info' => [
//                'store_id' => $spec_info->store_id,
//                'store_name' => $spec_info->store_name
//            ],
            'total_store' => [
                'kinds' => 1,
                'goods_amount' => $spec_info->price*$quantity,
                'quantity' => $quantity,
                'shipping_fee_info' => "满".$config['shipping']['min_free']."元包邮,不足金额运费".$config['shipping']['shipping_fee']."元"
            ],
            'goods'=>[],
        ];

        $temp['goods'][0]['pt_spec_id'] = $spec_info->pt_spec_id;
        $temp['goods'][0]['goods_id'] = $spec_info->goods_id;
        $temp['goods'][0]['goods_name'] = $spec_info->goods_name;
        $temp['goods'][0]['spec_id'] = $spec_info->spec_id;
        $temp['goods'][0]['specification'] = $specification ;
        $temp['goods'][0]['quantity'] = $quantity;
        $temp['goods'][0]['price'] = $spec_info->price;
        $temp['goods'][0]['stock'] = $spec_info->stock;

        /* 商品缩略图 */
//        empty($spec_info->default_image) && $spec_info->default_image = env('default_goods_image');
//        $temp['goods'][0]['goods_image'] = complete_url($spec_info->default_image);

        empty($spec_info->default_image2) && $spec_info->default_image2 = env('default_goods_image');
        $temp['goods'][0]['goods_image'] = complete_url($spec_info->default_image2);

        //获取默认地址
        $address= DB::table('address')->where('user_id',$user_id)->where('is_default',1)->first();

        //编辑返回值
        $return = $temp;

        if($address){
            $return['default_address'] = (array)$address;
        }else {
            $return['default_address'] = [];
        }

//        /* 配送方式 */
//        $cashierService = new CashierService();
//        /* 默认配送方式 */
//        $shipping_methods = $cashierService->getShippingMethods($store_id);
//        $return['default_shipping']          = $shipping_methods;

//        /* 配送费用=首件费用＋超出的件数*续件费用 */
//        if($shipping_methods){
//            $shipping_fee = $shipping_methods->first_price + ($temp['total_store']['quantity'] - 1) * $shipping_methods->step_price;
//        }else{
//            $shipping_fee = 0;
//        }

        /* 所有的拼团类的购买都是包邮的 */
        //获取店铺配置
//        $storeService = new StoreService();
//        $storeConfig = $storeService->getStoreConfig($spec_info->store_id);
//
//        /* 配送费为固定设置 */
//        if($temp['total_store']['goods_amount'] < $storeConfig['shipping']['min_free']){
//            $shipping_fee = $storeConfig['shipping']['shipping_fee'];
//        }else{
//            $shipping_fee = 0;
//        }

        $shipping_fee = 0;

        $return['shipping_fee'] = $shipping_fee;

        /* 默认使用快要过期的可用优惠券 */
        $couponService = new CouponService();
        $user_coupon = $couponService->getCashierCouponMethods($user_id,$temp['total_store']['goods_amount']);
        $return['default_coupon'] = $user_coupon;
        if($user_coupon){
            $coupon_fee = $user_coupon['coupon_value'];
        }else{
            $coupon_fee = 0;
        }

        $return['sub_amount'] = $temp['total_store']['goods_amount'] + $shipping_fee - $coupon_fee;

        //支付方式列表
        $pay_list = [
            [
                'payment_id'   => 1,
                'payment_name' => '支付宝',
                'payment_code' => 'alipay'
            ],
            [
                'payment_id'   => 2,
                'payment_name' => '微信',
                'payment_code' => 'wxPay'
            ]
        ];

        $return['pay_list'] = $pay_list;

        return $this->success($return);
    }

	public function createOrderByCart(){
	
        //**参数验证**	
	    if(!Input::has('addr_id')){
	        return $this->failure('请选择收货地址');
	    }

//        if(!Input::has('shipping_id')){
//            return $this->failure('请选择配送方式');
//        }

        if(!Input::has('tuan_id')){
            return $this->failure('参数错误');
        }

        if(!Input::has('pintuan_id')){
            return $this->failure('参数错误');
        }

        if(!Input::has('payment_id')){
            return $this->failure('请选择支付方式');
        }

	    $addr_id = Input::get('addr_id');
	    $user_id = Input::get('user_id');

	    $userinfo = DB::table('member')->where('user_id',$user_id)->first();
		if(!$userinfo){
		    return $this->failure("用户不存在");
		}

        if(empty($userinfo->user_name)){
            return $this->need_bind();
        }

        $address = Address::where('user_id',$user_id)
            ->where('addr_id',$addr_id)->first();
        if(!$address){
            return $this->failure("地址无效，请重新选择或填写新地址");
        }

		$store_id = Input::get('store_id',1);
		$storeinfo = DB::table('store')->where('store_id',$store_id)->get();
		if(!$storeinfo){
		    return $this->failure("店铺不存在");
		}

        //判断是否是全部购物车购买
		if(!Input::has('rec_ids')){//全部购物车
            $rec_id_list = [];
	    }else{
	    	$rec_id_list=explode(",",Input::get('rec_ids'));
	    }

        $goods = Input::get('goods','normal');
        $orderService = new OrderService();
        $goods_info = $orderService->getGoodsInfo($user_id,$rec_id_list,$store_id,$goods);

        /* 购物车是空的 */
        if ($goods_info === false)
        {
            return $this->failure('购物车是空的');
        }
        
        /*  检查库存 */
        $goods_beyond = $orderService->checkBeyondStock($goods_info['items']);
        if ($goods_beyond)
        {
            return $this->failure('库存不足',$goods_beyond); 
        }
        
        /* 在此获取生成订单的两个基本要素：用户提交的数据（POST），商品信息（包含商品列表，商品总价，商品总数量，类型），所属店铺 */
        $store_id = intval(Input::get('store_id',1));
        
        DB::beginTransaction();

        try {
            /* 优惠券数据处理 */
            $coupon_type = Input::get('coupon_type','coupon');
            $coupon_sn = Input::get('coupon_sn',0);
            if ($goods_info['allow_coupon'] && $coupon_type && $coupon_sn)
            {
                if(!in_array($coupon_type, array('coupon','cashcoupon'))){
                    return $this->failure('参数不对');
                }
                $coupon_info = [];
                if($coupon_type=='coupon') {
                    $couponService = new CouponService();
                    $coupon_info = $couponService->getCouponInfo($coupon_sn);
                } /*else {
                    $coupon_info = DB::table('cash_coupon_sn')->join('cash_coupon','cash_coupon_sn.coupon_id','=','cash_coupon.coupon_id')
                        ->where('cash_coupon.store_id',$store_id)->where('cash_coupon_sn.coupon_sn',$coupon_sn)
                        ->select('cash_coupon.*','cash_coupon_sn.remain_times')->first();
                }   */            


                if (empty($coupon_info)){
                    return $this->failure('无效的优惠券编号');
                }

                $coupon_info = $coupon_info->toArray();

                if ($coupon_info['remain_times'] < 1){
                    return $this->failure('该优惠券已被使用');
                }
                $time = gmtime();
                if ($coupon_info['coupon']['start_time'] > $time){
                    return $this->failure('该优惠券尚不能使用');
                }
    
                if ($coupon_info['coupon']['end_time'] < $time)
                {
                    return $this->failure('该优惠券已过期');
                }
                if ($coupon_info['coupon']['min_amount'] > $goods_info['amount'])
                {
                     return $this->failure('未达到使用金额');
                }
                unset($time);
                $goods_info['discount'] = $coupon_info['coupon']['coupon_value'];
                $goods_info['coupon_sn'] = $coupon_sn;
            }

            $order_sn = $orderService->getOrderSn();
            /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
            $submit = $orderService->submitOrder(array(
                'goods_info'    =>  $goods_info,        //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
                'post'          =>  Input::all(),       //用户填写的订单信息
                'order_sn'      =>  $order_sn           //订单号

            ));

            if (!$submit['order_id'])
            {
                return $this->failure($submit['error']);
            }

            $order_id = $submit['order_id'];

            /* 下单完成后清理商品，如清空购物车，或将团购拍卖的状态转为已下单之类的 */
            $orderService->clearGoods($user_id,$rec_id_list,$goods);

            //减去优惠券使用次数
            DB::table('coupon_sn')->where('coupon_sn',$coupon_sn)->decrement('remain_times',1);

            /* 更新下单次数 */
            $goods_ids = array();
            foreach ($goods_info['items'] as $goods)
            {
                $goods_ids[] = $goods['goods_id'];
            }
            DB::table('goods_statistics')->whereIn('goods_id',$goods_ids)->increment('orders');
            
            DB::commit();

            /* 获取订单信息 */
            $order_info = DB::table('order')->where('order_id',$order_id)->where('buyer_id',$user_id)->first();
            if (empty($order_info))
            {
                return $this->failure('没有该订单');
            }
            //订单商品信息
            $order_goods = DB::table('order_goods')->where('order_id',$order_id)->get();
            if(empty($order_goods)){
            	return $this->failure('订单中没有商品');
            }
            $detail = '';
            if(count($order_goods)>1){
            	$order_name = '多商品购买';
            	foreach($order_goods as $g){
            		$detail .= $g->goods_name . '+';
            	}
            	$goods_detail = substr($detail, 0, -1);
            }else{
            	$ordergoods = current($order_goods);
            	$order_name = $ordergoods->goods_name;
            	$goods_detail = $ordergoods->goods_name;
            }
            $order_info->order_name = $order_name;
            $order_info->goods_detail = $goods_detail;

            /* 订单有效性判断 */
            if ($order_info->payment_code != 'cod'
                && $order_info->status != ORDER_PENDING
                && $order_info->status != ORDER_ACCEPTED){
                return $this->failure('订单不可支付');;
            }
            
            return $this->success($order_info);

        } catch(Exception $e){
            DB::rollback();
            throw $e;
        }
		
	}
	
	public function createOrderByGoods(){
	
	 	//**参数验证**
	    if(!Input::has('addr_id')){
	        return $this->failure('请选择收货地址');
	    }

	    if(!Input::has('payment_id')){
	        return $this->failure('请选择支付方式');
	    }

        if(!Input::has('tuan_id')){
            return $this->failure('参数错误');
        }

        if(!Input::has('pintuan_id')){
            return $this->failure('参数错误');
        }

//        if(!Input::has('shipping_id')){
//            return $this->failure('请选择配送方式');
//        }

        if(!Input::has('quantity')){
            return $this->failure('请选择购买数量');
        }

		$user_id = Input::get('user_id');
		$userinfo = DB::table('member')->where('user_id',$user_id)->first();
		if(!$userinfo){
		    return $this->failure("用户不存在");
		}

        if(empty($userinfo->user_name)){
            return $this->need_bind();
        }

		$store_id = Input::get('store_id');
		$storeinfo = DB::table('store')->where('store_id',$store_id)->get();
		if(!$storeinfo){
		    return $this->failure("超市不存在");
		}

		$spec_id = Input::get('spec_id');
        $quantity = Input::get('quantity',1);

        $orderService = new OrderService();
		$goods_info = $orderService->getSingleGoodsInfo($spec_id,$quantity,$store_id);

        if ($goods_info === false)
        {
            /* 购物车是空的 */
            return $this->failure('商品已下架');
        }

        /*  检查库存 */
        $goods_beyond = $orderService->checkBeyondStock($goods_info['items']);

        if ($goods_beyond)
        {
            return $this->failure('库存不足',$goods_beyond);
        }

		/* 在此获取生成订单的两个基本要素：用户提交的数据（POST），商品信息（包含商品列表，商品总价，商品总数量，类型），所属店铺 */

        DB::beginTransaction();

        try {
            /* 优惠券数据处理 */
            $coupon_type = Input::get('coupon_type','coupon');
            $coupon_sn = Input::get('coupon_sn',0);
            if ($goods_info['allow_coupon'] && $coupon_type && $coupon_sn)
            {
                if(!in_array($coupon_type, array('coupon','cashcoupon'))){
                    return $this->failure('参数不对');
                }
                $coupon_info = [];
                if($coupon_type=='coupon') {
                    $couponService = new CouponService();
                    $coupon_info = $couponService->getCouponInfo($coupon_sn);
                } /*else {
                    $coupon_info = DB::table('cash_coupon_sn')->join('cash_coupon','cash_coupon_sn.coupon_id','=','cash_coupon.coupon_id')
                        ->where('cash_coupon.store_id',$store_id)->where('cash_coupon_sn.coupon_sn',$coupon_sn)
                        ->select('cash_coupon.*','cash_coupon_sn.remain_times')->first();
                }   */


                if (empty($coupon_info)){
                    return $this->failure('无效的优惠券编号');
                }

                $coupon_info = $coupon_info->toArray();

                if ($coupon_info['remain_times'] < 1){
                    return $this->failure('该优惠券已被使用');
                }
                $time = gmtime();
                if ($coupon_info['coupon']['start_time'] > $time){
                    return $this->failure('该优惠券尚不能使用');
                }

                if ($coupon_info['coupon']['end_time'] < $time)
                {
                    return $this->failure('该优惠券已过期');
                }
                if ($coupon_info['coupon']['min_amount'] > $goods_info['amount'])
                {
                    return $this->failure('未达到使用金额');
                }
                unset($time);
                $goods_info['discount'] = $coupon_info['coupon']['coupon_value'];
                $goods_info['coupon_sn'] = $coupon_sn;
            }

            $order_sn = $orderService->getOrderSn();

            /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
            $submit = $orderService->submitOrder(array(
                'goods_info'    =>  $goods_info,        //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
                'post'          =>  Input::all(),       //用户填写的订单信息
                'order_sn'      =>  $order_sn           //订单号

            ));

            if (!$submit['order_id'])
            {
                return $this->failure($submit['error']);
            }

            $order_id = $submit['order_id'];

            //减去优惠券使用次数
            DB::table('coupon_sn')->where('coupon_sn',$coupon_sn)->decrement('remain_times',1);

            /* 更新下单次数 */
            $goods_ids = array();
            foreach ($goods_info['items'] as $goods)
            {
                $goods_ids[] = $goods['goods_id'];
            }

            DB::table('goods_statistics')->whereIn('goods_id',$goods_ids)->increment('orders');

            DB::commit();

            $order_info = DB::table('order')->where('order_id',$order_id)->where('buyer_id',$user_id)->get();
        	if (empty($order_info))
        	{
            	return $this->failure('没有该订单');
        	}

        	$order_info = current($order_info);

        	$order_goods = DB::table('order_goods')->where('order_id',$order_id)->get();

            if(empty($order_goods)){
            	return $this->failure('订单中没有商品');
            }

            $ordergoods = current($order_goods);
            $order_name = $ordergoods->goods_name;
            $goods_detail = $ordergoods->goods_name;

	        /* 订单有效性判断 */
	        if ($order_info->payment_code != 'cod'
                && $order_info->status !=ORDER_PENDING
                && $order_info->status != ORDER_ACCEPTED){
	            return $this->failure('订单不可支付');;
	        }

			$order_info->order_name = $order_name;
            $order_info->goods_detail = $goods_detail;

            return $this->success($order_info);

        } catch(Exception $e){
            DB::rollback();
            throw $e;
        }

	}

    public function createOrderByPintuan(){        
        //**参数验证**
        if(!Input::has('addr_id')){
            return $this->failure('请选择收货地址');
        }

        if(!Input::has('payment_id')){
            return $this->failure('请选择支付方式');
        }

        if(!Input::has('quantity')){
            return $this->failure('请选择购买数量');
        }

        $pintuan_id = Input::get('pintuan_id');//拼团id
        $tuan_id = Input::get('tuan_id',0);//团id

        $user_id = Input::get('user_id');
        $userinfo = DB::table('member')->where('user_id',$user_id)->first();
        if(!$userinfo){
            return $this->failure("用户不存在");
        }

        if(empty($userinfo->user_name)){
            return $this->need_bind();
        }

        $store_id = Input::get('store_id');
        $storeinfo = DB::table('store')->where('store_id',$store_id)->get();
        if(!$storeinfo){
            return $this->failure("超市不存在");
        }

        $spec_id = Input::get('spec_id');
        $quantity = Input::get('quantity',1);

        $pintuanService = new PintuanService();

        //检查是否可以开团或者参团
        $returnCheck = $pintuanService->checkPintuan($pintuan_id,$tuan_id,$user_id);
        if($returnCheck!= ""){
            return $this->failure($returnCheck);
        }

        /* 是否有商品 */
        $spec_info = $pintuanService->getPintuanSpec($spec_id);

        $orderService = new OrderService();
        $goods_info = $orderService->getPintuanGoodsInfo($spec_info->pintuan_type,$spec_id,$quantity,$store_id);

        if ($goods_info['quantity'] > $spec_info->stock){
            return $this->failure('库存不足');
        }

        if (($spec_info->max_per_user > 0) && ($goods_info['quantity'] > $spec_info->max_per_user)){
            return $this->failure('该商品每个人单次购买不可超过'.$spec_info->max_per_user.'件');
        }

        /*  检查库存 */
        $goods_beyond = $orderService->checkBeyondStock($goods_info['items']);

        if ($goods_beyond)
        {
            return $this->failure('库存不足',$goods_beyond);
        }

        /* 在此获取生成订单的两个基本要素：用户提交的数据（POST），商品信息（包含商品列表，商品总价，商品总数量，类型），所属店铺 */

        DB::beginTransaction();

        try {
            /* 优惠券数据处理 */
            $coupon_type = Input::get('coupon_type','coupon');
            $coupon_sn = Input::get('coupon_sn',0);
            if ($goods_info['allow_coupon'] && $coupon_type && $coupon_sn)
            {
                if(!in_array($coupon_type, array('coupon','cashcoupon'))){
                    return $this->failure('参数不对');
                }
                $coupon_info = [];
                if($coupon_type=='coupon') {
                    $couponService = new CouponService();
                    $coupon_info = $couponService->getCouponInfo($coupon_sn);
                } /*else {
                    $coupon_info = DB::table('cash_coupon_sn')->join('cash_coupon','cash_coupon_sn.coupon_id','=','cash_coupon.coupon_id')
                        ->where('cash_coupon.store_id',$store_id)->where('cash_coupon_sn.coupon_sn',$coupon_sn)
                        ->select('cash_coupon.*','cash_coupon_sn.remain_times')->first();
                }   */


                if (empty($coupon_info)){
                    return $this->failure('无效的优惠券编号');
                }

                $coupon_info = $coupon_info->toArray();

                if ($coupon_info['remain_times'] < 1){
                    return $this->failure('该优惠券已被使用');
                }
                $time = gmtime();
                if ($coupon_info['coupon']['start_time'] > $time){
                    return $this->failure('该优惠券尚不能使用');
                }

                if ($coupon_info['coupon']['end_time'] < $time)
                {
                    return $this->failure('该优惠券已过期');
                }
                if ($coupon_info['coupon']['min_amount'] > $goods_info['amount'])
                {
                    return $this->failure('未达到使用金额');
                }
                unset($time);
                $goods_info['discount'] = $coupon_info['coupon']['coupon_value'];
                $goods_info['coupon_sn'] = $coupon_sn;
            }

            $order_sn = $orderService->getOrderSn();

            /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
            $submit = $orderService->submitOrder(array(
                'goods_info'    =>  $goods_info,        //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
                'post'          =>  Input::all(),       //用户填写的订单信息
                'order_sn'      =>  $order_sn           //订单号

            ));

            if (!$submit['order_id'])
            {
                return $this->failure($submit['error']);
            }

            $order_id = $submit['order_id'];
            
//            //@TODO 已经放到支付回调中，等待测试 测试通过删除代码
//            //添加团信息
//            $pintuanService->createOrEnterTuan($pintuan_id,$user_id,$order_id,$tuan_id,$quantity);

            //减去优惠券使用次数
            DB::table('coupon_sn')->where('coupon_sn',$coupon_sn)->decrement('remain_times',1);

            /* 更新下单次数 */
            $goods_ids = array();
            foreach ($goods_info['items'] as $goods)
            {
                $goods_ids[] = $goods['goods_id'];
            }

            DB::table('goods_statistics')->whereIn('goods_id',$goods_ids)->increment('orders');

            DB::table('pintuan_statistics')->where('pintuan_id',$pintuan_id)->increment('orders');

            DB::commit();

            $order_info = DB::table('order')->where('order_id',$order_id)->where('buyer_id',$user_id)->get();
            if (empty($order_info))
            {
                return $this->failure('没有该订单');
            }

            $order_info = current($order_info);

            $order_goods = DB::table('order_goods')->where('order_id',$order_id)->get();

            if(empty($order_goods)){
                return $this->failure('订单中没有商品');
            }

            $ordergoods = current($order_goods);
            $order_name = $ordergoods->goods_name;
            $goods_detail = $ordergoods->goods_name;

            /* 订单有效性判断 */
            if ($order_info->payment_code != 'cod'
                && $order_info->status !=ORDER_PENDING
                && $order_info->status != ORDER_ACCEPTED){
                return $this->failure('订单不可支付');;
            }

            $order_info->order_name = $order_name;
            $order_info->goods_detail = $goods_detail;

            return $this->success($order_info);

        } catch(Exception $e){
            DB::rollback();
            throw $e;
        }

    }

	/**
     *    确认支付
     *    @return    void
     */
    public function gotoPay()
    {    	
    	$user_id = Input::get('user_id');
        $order_id = Input::get('order_id',0);
        $payment_id = Input::get('payment_id',0);
        if (!$order_id)
        {
            return $this->failure('未找到订单');
        }
        if (!$payment_id)
        {
             return $this->failure('未找到订单');
        }

        $orderService = new OrderService();


        $order_info  =  $orderService->getOrderInfo($user_id,$order_id);
//            DB::table('order')
//        	->where('order_id',$order_id)
//        	->where('buyer_id',$user_id)
//        	->get();
        if (empty($order_info))
        {
            return $this->failure('未找到订单');
        }

    	/* 订单有效性判断 */
        if ($order_info->payment_code != 'cod' && $order_info->status != ORDER_PENDING)
        {
            return $this->failure('未找到订单');
        }

        /* 验证支付方式 */
        $payment_info  = DB::table('payment')
        	->where('payment_id',$payment_id)
        	->first();

        if (!$payment_info)
        {
            return $this->failure('没有这种支付方式');
        }

        /* 保存支付方式 */
//        $edit_data = array(
//            'payment_id'    =>  $payment_info->payment_id,
//            'payment_code'  =>  $payment_info->payment_code,
//            'payment_name'  =>  $payment_info->payment_name,
//        );

//        DB::table('order')->where('order_id',$order_id)->update($edit_data);

        $order_info->payment_id = $payment_info->payment_id;
        $order_info->payment_code = $payment_info->payment_code;
        $order_info->payment_name = $payment_info->payment_name;

        $order_info->save();

        $url = config("pms.WEB_URL")."/index.php?app=cashierapi&act=apigopayment&order_id=".$order_id."&user_id=".$user_id;
        //dd($url);
        $ch = curl_init($url) ;
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        $output = curl_exec($ch);
        //dd($output);
        return $this->success(null);
    }

    /**
     * 支付回调 
     * 
     */
	public function notify(){	
		return $this->success(null);
	}

}
